package com.web.checkbox;

import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;

public class CheckBoxUtil {
	public static List retrieveNodeInfos() {
		List coll = new ArrayList();
		String driverName = "com.mysql.jdbc.Driver";
		String host = "localhost";
		String port = ":3306";
		String serverID = "cms";
		String userName = "root";
		String userPwd = "123456";
		String url = "jdbc:mysql://" + host + port + "/" + serverID;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			Class.forName(driverName).newInstance();
			conn = DriverManager.getConnection(url, userName, userPwd);
			String sql = "select * from category";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			CheckBoxInfo info = null;
			while (rs != null && rs.next()) {
				info = new CheckBoxInfo();
				info.setNodeId(rs.getInt(1));
				info.setNodeName(rs.getString(2));
				coll.add(info);
			}
			// if(rs!=null){
			// rs.close();
			// rs=null;
			// }
			// if(ps!=null){
			// ps.close();
			// ps=null;
			// }
		} catch (Exception e) {
			System.out.println(e);
		}

		return coll;
	}

	public static String createTreeInfo(List alist) {
		StringBuffer contents = new StringBuffer();
		CheckBoxInfo info = null;
		for (int max = alist.size(), i = 0; i < max; i++) {
			info = (CheckBoxInfo) alist.get(i);
			// define elements of array			
			contents.append("<input type=\"checkbox\" name=\"aa\" value=\"");
			contents.append(info.getNodeId());
			contents.append("\">");
			contents.append(info.getNodeName());
			contents.append("\n");
		}
		contents.append("<input type=submit value=\"submit\">");
		return contents.toString();
	}

	public static void main(String[] args) {
		List alist = CheckBoxUtil.retrieveNodeInfos();
		// TreeInfo info = null;
		// for(Iterator i = c.iterator();i.hasNext();){
		// info = (TreeInfo)i.next();
		// System.out.println("*****" + info.getNodeName());
		// }
		System.out.println(CheckBoxUtil.createTreeInfo(alist));
	}
}